﻿using AutoMapper;
using MediatR;
using Traceability.App.Apilication.Common;
using Traceability.App.Domain;
using Traceability.App.DTOS;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure.Interfance;

namespace Traceability.App.Apilication.Handler
{
    public class InquireTranHandler : IRequestHandler<InquireTranCommon, ApiPaimg<TraceabilityDTO>>
    {
        private readonly IBaseRespository<TraceabilityModel> trancebilityRepo;
        private readonly IMapper mapper;
        private readonly IBaseRespository<GoodsModel> goodsRepo;

        public InquireTranHandler(IBaseRespository<TraceabilityModel> trancebilityRepo,IMapper mapper, IBaseRespository<GoodsModel> goodsRepo)
        {
            this.trancebilityRepo = trancebilityRepo;
            this.mapper = mapper;
            this.goodsRepo = goodsRepo;
        }
        public Task<ApiPaimg<TraceabilityDTO>> Handle(InquireTranCommon request, CancellationToken cancellationToken)
        {
            ApiPaimg<TraceabilityDTO> res =new ApiPaimg<TraceabilityDTO>();

            var trance = trancebilityRepo.GetAll().Where(x => x.Delete_Identifier == false);
            var goods = goodsRepo.GetAll();


            if (!string.IsNullOrEmpty(request.Production_Batch))
            {
                trance = trance.Where(x => x.Production_Batch==request.Production_Batch);
            }


            var linq = from a in trance
                       join b in goods
                       on a.Product_Name equals b.Goods_ID
                       select new TraceabilityDTO
                       {
                           Traceability_ID = a.Traceability_ID,
                           Product_Name = a.Product_Name,
                           Production_Batch = a.Production_Batch,
                           Quality_Guarantee_Period = a.Quality_Guarantee_Period,
                           Production_License_Number = a.Production_License_Number,
                           Manufacturing_Enterprise = a.Manufacturing_Enterprise,
                           CreateName = a.CreateName,
                           CreateTime = a.CreateTime,
                           UpdateName = a.UpdateName,
                           UpdateTime = a.UpdateTime,
                           Cover_Image = a.Cover_Image,
                           Delete_Identifier = a.Delete_Identifier,
                           Goods_Name = b.Goods_Name,
                       };

            res.Code = ApiEnum.Success;
            res.ToTaCount = linq.Count();
            res.ToTaPage = (int)Math.Ceiling(res.ToTaCount * 1.0 / request.PageSize);
            res.PageData = linq.OrderBy(x => x.Traceability_ID).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            return Task.FromResult(res);


        }
    }
}
